<template>
    <div class="search-container">
        <div class="search-bar">
            <input type="text" v-model="search" placeholder="应用S23-5班24贾认真——请输入搜索关键词" />
            <button @click="searchHandle">搜索</button>
        </div>
        <div v-if="loading" class="loading">加载中...</div>
        <div v-if="error" class="error">{{ error }}</div>
        <ul class="search-results">
            <router-link 
                tag="li"
                :to="{name:'Player',params:{id:item.id,name:item.name,image:encodeURIComponent(item.album.artist.img1v1Url)}}" 
                v-for="(item, index) in searchData" 
                :key="index"
                class="search-item">
                {{ item.name }}
            </router-link>
        </ul>
    </div>
</template>

<script>
export default {
    name: "Search",
    data() {
        return {
            search: "",
            searchData: [],
            loading: false,
            error: null
        };
    },
    mounted() {},
    methods: {
        searchHandle() {
            if (!this.search.trim()) {
                alert("请输入搜索关键词");
                return;
            }

            this.loading = true;
            this.error = null;

            this.$api.getSearch({
                keywords: this.search
            }).then(res => {
                console.log("搜索数据", res);
                this.searchData = res.result.songs;
            }).catch(error => {
                console.error("搜索请求失败", error);
                this.error = "搜索请求失败，请重试";
            }).finally(() => {
                this.loading = false;
            });
        }
    }
};
</script>

<style scoped>
.search-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
    background-color: #f9f9f9;
    min-height: 100vh;
}

.search-bar {
    display: flex;
    width: 100%;
    max-width: 600px;
    margin-bottom: 20px;
}

.search-bar input {
    flex: 1;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    margin-right: 10px;
    box-sizing: border-box;
}

.search-bar button {
    padding: 10px 20px;
    background-color: #007bff;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.search-bar button:hover {
    background-color: #0056b3;
}

.search-results {
    width: 100%;
    max-width: 600px;
    list-style-type: none;
    padding: 0;
}

.search-item {
    padding: 10px;
    border-bottom: 1px solid #ddd;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.search-item:hover {
    background-color: #f0f0f0;
}

.loading, .error {
    margin-bottom: 20px;
    color: #ff0000;
    font-weight: bold;
}
</style>